package com.sniff.atp.service.wms.storage;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.sniff.atp.dto.ContentDTO;
import com.sniff.atp.dto.WMSLoginDTO;
import com.sniff.atp.enums.api.WmsAPI;
import com.sniff.atp.enums.status.WmsRegionStatus;
import com.sniff.atp.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

/**
 * @BelongsProject: sniff-atp
 * @BelongsPackage: com.sniff.atp.service.wms.storage
 * @Author: zxy
 * @CreateTime: 2022-11-09 13:32
 * @Description: WMS: 组合操作
 * @Version: 1.0
 */
@Service
public class WMSCombinationOperationService {

    @Autowired
    private WMSStorageService wmsStorageService;

    /**
     * WMS: 组合列表查询
     */
    public String packTakePage(WMSLoginDTO wmsLoginDTO, String packCode){
        String data = "{\"pageSize\":10,\"pageNum\":1}";
        JSONObject param = JsonUtil.strToJSONObject(data);

        if (StringUtils.isNotEmpty(packCode)){
            param.put("packCode", packCode);
        }

        String result = new HttpClientUtil(Headers.setWmsHeader(wmsLoginDTO)).doPostJson(WmsAPI.WMS_API28.getApi(), param);
        return result;
    }

    /**
     * WMS: 组合待拣货查询
     */
    public String packAbleTaskPage(WMSLoginDTO wmsLoginDTO){
        String data = "{\"pageSize\":10,\"pageNum\":1}";
        JSONObject param = JsonUtil.strToJSONObject(data);

        String result = new HttpClientUtil(Headers.setWmsHeader(wmsLoginDTO)).doPostJson(WmsAPI.WMS_API29.getApi(), param);
        return result;
    }

    /**
     * WMS: 组合创建PDA拣货任务
     */
    public String createPackBatch(WMSLoginDTO wmsLoginDTO, String packCode){
        JSONArray param = new JSONArray();
        param.add(packCode);

        String result = new HttpClientUtil(Headers.setWmsHeader(wmsLoginDTO)).doPostJson(WmsAPI.WMS_API30.getApi(), param);
        return result;
    }

    /**
     * WMS: 组合任务列表查询
     */
    public String pcPickTaskPage(WMSLoginDTO wmsLoginDTO, String packCode){
        JSONObject param = JsonUtil.readJson("wms/pcPickTaskPage");
        param.replace("packCode", packCode);

        String result = new HttpClientUtil(Headers.setWmsHeader(wmsLoginDTO)).doPostJson(WmsAPI.PC_PICK_TASK_PAGE.getApi(), param);
        return result;
    }

    /**
     * PDA：组合拣货任务详情
     */
    public String pickTaskDetail(WMSLoginDTO wmsLoginDTO, String pickCode){
        HashMap<String, String> param = new HashMap<>();
        param.put("pickCode", pickCode);

        String result = new HttpClientUtil(Headers.setWmsHeader(wmsLoginDTO)).doGet(WmsAPI.WMS_API32.getApi(), param);
        return result;
    }

    /**
     * PDA: 组合拣货操作
     */
    public String doPick(WMSLoginDTO wmsLoginDTO, String pickCode, String pkgCode){
        HashMap<String, String> param = new HashMap<>();
        param.put("pickCode", pickCode);
        param.put("pkgCode", pkgCode);

        String result = new HttpClientUtil(Headers.setWmsHeader(wmsLoginDTO)).doGet(WmsAPI.WMS_API33.getApi(), param);
        return result;
    }

    /**
     * PDA: 组合配货操作
     */
    public String sorting(WMSLoginDTO wmsLoginDTO, String pickCode, String pkgCode){
        JSONObject param = new JSONObject();
        param.put("pickCode", pickCode);
        param.put("pkgCode", pkgCode);

        String result = new HttpClientUtil(Headers.setWmsHeader(wmsLoginDTO)).doPostJson(WmsAPI.SOW_QUERY.getApi(), param);
        return result;
    }

    /**
     * 校验拣货批次
     *
     * @param pickCode
     * @return
     */
    private String checkPick(WMSLoginDTO wmsLoginDTO, String pickCode) {
        HashMap<String, String> param = new HashMap<>();
        param.put("pickCode", pickCode);

        String result = new HttpClientUtil(Headers.setWmsHeader(wmsLoginDTO)).doGet(WmsAPI.WMS_CHECK_PICK.getApi(), param);
        return result;
    }

    /**
     * WMS: 组合任务完成
     */
    public String doPackFinish(WMSLoginDTO wmsLoginDTO, String pickCode, String packCode, String pkgCode){
        HashMap<String, String> param = new HashMap<>();
        param.put("packCode", packCode);
        param.put("pickCode", pickCode);
        param.put("pkgCode", pkgCode);

        String result = new HttpClientUtil(Headers.setWmsHeader(wmsLoginDTO)).doGet(WmsAPI.WMS_API34.getApi(), param);
        return result;
    }

    /**
     * WMS：获取组合分拣框
     */
    public String getPackBasket(WMSLoginDTO wmsLoginDTO, String packCode){
        HashMap<String, String> param = new HashMap<>();
        param.put("packCode", packCode);

        return  new HttpClientUtil(Headers.setWmsHeader(wmsLoginDTO)).doGet(WmsAPI.WMS_GET_PACK_BASKET.getApi(), param);
    }

    /**
     * wms：组合分拣信息
     */
    public String getBasketInfo(WMSLoginDTO wmsLoginDTO, String basketCode){
        HashMap<String, String> param = new HashMap<>();
        param.put("basketCode", basketCode);

        return  new HttpClientUtil(Headers.setWmsHeader(wmsLoginDTO)).doGet(WmsAPI.WMS_GET_PACK_BASKET_INFO.getApi(), param);
    }

    /**
     * WMS：完成组合分拣
     */
    public String doBasketPackFinish(WMSLoginDTO wmsLoginDTO, String packCode, String basketCode){
        JSONObject param = new JSONObject();
        param.put("packCode", packCode);
        param.put("basketCode", basketCode);
        param.put("volume", "XL");

        return  new HttpClientUtil(Headers.setWmsHeader(wmsLoginDTO)).doPostJson(WmsAPI.WMS_DO_PACK_BASKET_FINISH.getApi(), param);
    }

    /**
     * WMS：组合操作流程
     */
    public String combinationProcess(WMSLoginDTO wmsLoginDTO, String packCode, String warehouse){
        String s = packTakePage(wmsLoginDTO, packCode);

        String dataTotal= JsonUtil.extractString(s, "data.total");
        if (dataTotal.equals("0")){
            wmsStorageService.switchHouse(wmsLoginDTO, warehouse);

        }

        LogUtil.warn("【WMS组合】查询组合列表，组合任务编号：" + packCode);
        packAbleTaskPage(wmsLoginDTO);
        LogUtil.warn("【WMS组合】查询待拣货列表!!");
        createPackBatch(wmsLoginDTO, packCode);
        LogUtil.warn("【WMS组合】创建组合拣货任务！！！");


        JSONArray pickCodes = new JSONArray();

        // 组合任务存在多个拣货批次
        String pcPickTaskPage = pcPickTaskPage(wmsLoginDTO, packCode);
        String mainPkgCode = "";

        JSONArray pickCodeRecords = JsonUtil.extractJSONArray(pcPickTaskPage, "data.records[0].packRecords");

        for (int i = 0; i < pickCodeRecords.size(); i++) {
            String pickCode =  pickCodeRecords.getJSONObject(i).getString("pickCode");


            LogUtil.warn("【WMS组合】查询任务列表，获取拣货任务单号：" + pickCode);

            String pickTaskDetail = pickTaskDetail(wmsLoginDTO, pickCode);
            LogUtil.warn("【WMS组合】PDA查询组合拣货任务详情！！！");
            JSONArray data = JsonUtil.extractJSONArray(pickTaskDetail, "data");

            JSONArray pkgCodes = new JSONArray();

            for (int j = 0; j < data.size(); j++) {
                JSONObject jsonObject = data.getJSONObject(j);
                mainPkgCode = jsonObject.getString("mainPkgCode");
                String pkgCode = jsonObject.getString("pkgCode");
                pkgCodes.add(pkgCode);

                doPick(wmsLoginDTO, pickCode, pkgCode);
                LogUtil.warn("【WMS组合】PDA组合拣货扫描批次号：" + pkgCode);

            }

            String checkPickResult = checkPick(wmsLoginDTO, pickCode);
            String needPick = JsonUtil.extractString(checkPickResult, "data.needPick");

            if(needPick.equals("1")) {
                for (Object obj : pkgCodes) {
                    String pkgCode = obj.toString();
                    sorting(wmsLoginDTO, pickCode, pkgCode);
                    LogUtil.warn("【WMS组合】PDA组合拣货配货扫描批次号：" + pkgCode);
                }
//                doPackFinish(wmsLoginDTO, pickCode, packCode, mainPkgCode);
                LogUtil.warn("【WMS组合】PDA组合任务组合完成");
            }

            pickCodes.add(pickCode);
        }

        productCombination(wmsLoginDTO,packCode);

        JSONObject object = new JSONObject();
        object.put("pkgCode", mainPkgCode);
        object.put("pickCode", pickCodes);
        object.put("packCode", packCode);
        return object.toJSONString();
    }


    /**
     * wms：组合操作流程
     */
    public void productCombination(WMSLoginDTO wmsLoginDTO, String packCode){
        pcPickTaskPage(wmsLoginDTO, packCode);

        // 获取组合分拣框
        String packBasket = getPackBasket(wmsLoginDTO, packCode);

        JSONArray data = JsonUtil.extractJSONArray(packBasket, "data");

        for (int i = 0; i < data.size(); i++) {
            String basketCode = data.getJSONObject(i).getString("basketCode");

            // 获取分拣框信息
            getBasketInfo(wmsLoginDTO, basketCode);

            // 完成分拣组合
            doBasketPackFinish(wmsLoginDTO, packCode, basketCode);
        }


    }



    /**
     * WMS： 组合商品组合完成，主商品移库上架操作
     */
    public void combinationStorage(WMSLoginDTO wmsLoginDTO, String pkgCode){
        String queryPkg4Transfer = wmsStorageService.queryPkg4Transfer(wmsLoginDTO, pkgCode);
        LogUtil.warn("【wms入库】移库查询批次，批次号：" + pkgCode);

        JSONObject object1 = JSON.parseObject(queryPkg4Transfer);
        JSONObject data1 = object1.getJSONObject("data");
        Integer combinationProductItemFlag = data1.getInteger("combinationProductItemFlag");

        // 判断批次是否为组合商品批次: 1 组合商品， 0普通商品；组合商品只能入质检区
        if (combinationProductItemFlag != null && 1 == combinationProductItemFlag){
            JSONObject object2 = wmsStorageService.regionList(wmsLoginDTO, WmsRegionStatus.WMS_REGION_STATUS3.getBindStatus());
            String regionCode = object2.getString("regionCode");
            String regionName = object2.getString("regionName");

            wmsStorageService.doTransfer(wmsLoginDTO, data1.toJSONString(), regionCode, regionName);
            LogUtil.warn("【wms入库】移库提交操作！！");
        } else {
            JSONObject object2 = wmsStorageService.regionList(wmsLoginDTO, WmsRegionStatus.WMS_REGION_STATUS4.getBindStatus());
            String regionCode = object2.getString("regionCode");
            String regionName = object2.getString("regionName");

            wmsStorageService.doTransfer(wmsLoginDTO, data1.toJSONString(), regionCode, regionName);
            LogUtil.warn("【wms入库】移库提交操作！！");
        }

        String transfer = wmsStorageService.getTransfer(wmsLoginDTO, pkgCode);
        LogUtil.warn("【wms入库】移库确认，批次查询；批次号：" + pkgCode);

        JSONObject object2 = JSON.parseObject(transfer);
        JSONObject data2 = object2.getJSONObject("data");
        wmsStorageService.doConfirm(wmsLoginDTO, data2.toJSONString());
        LogUtil.warn("【wms入库】移库确认，提交完成！！！");

        wmsStorageService.shelve(wmsLoginDTO, pkgCode);
        LogUtil.warn("【PDA操作】PDA执行上架操作，批次号：" + pkgCode);
    }

    /**
     * WMS: 根据订单查询组合任务
     */
    public boolean platformOrderCombinationProcess(WMSLoginDTO wmsLoginDTO, String platformOrderNo){
        List<JSONObject> select = DBUtil.select("WMS-查询组合任务", new ContentDTO("", platformOrderNo));
        if (select.size() == 0){
            return false;
        }
        for (JSONObject o: select) {
            String packCode = o.getString("pack_code");
            String warehouse = o.getString("warehouse");
            // 组合操作
            String s = combinationProcess(wmsLoginDTO, packCode, warehouse);
            String pkgCode = JsonUtil.strToJSONObject(s).getString("pkgCode");
            // 组合商品入库成品区
            combinationStorage(wmsLoginDTO, pkgCode);
        }

        return true;
    }
}
